<!--
 * @Description: 
 * @Author: charles
 * @Date: 2021-05-05 22:02:56
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-18 19:33:53
-->
<template>
  <div ref="root" style="height: 95%"></div>
</template>

<script>
import { Liquid, measureTextWidth } from "@antv/g2plot";
import { ref, onMounted, onUnmounted } from "vue";

export default {
  // 组件名称
  name: "demo",
  // 组件状态值
  setup() {
    const root = ref(null);
    let plot = null;

    let data_liquid = ref([]);
    const loadData = async () => {
      data_liquid.value = [
      ];
    };

    const initChart = () => {
      plot = new Liquid(root.value, {
        data: data_liquid.value,
        percent: 0.26,
        radius: 0.8,
        statistic: {
          title: {
            formatter: () => "考研率",
            style: ({ percent }) => ({
              fill: percent > 0.65 ? "white" : "yellow",
            }),
          },
          content: {
            style: ({ percent }) => ({
              fontSize: 60,
              lineHeight: 1,
              fill: percent > 0.65 ? "white" : "yellow",
            }),
            customHtml: (container, view, { percent }) => {
              const { width, height } = container.getBoundingClientRect();
              const d = Math.sqrt(
                Math.pow(width / 2, 2) + Math.pow(height / 2, 2)
              );
              const text = `占比 ${(percent * 100).toFixed(0)}%`;
              const textWidth = measureTextWidth(text, { fontSize: 60 });
              const scale = Math.min(d / textWidth, 1);
              return `<div style="width:${d}px;display:flex;align-items:center;justify-content:center;font-size:${scale}em;line-height:${
                scale <= 1 ? 1 : "inherit"
              }">${text}</div>`;
            },
          },
        },
        liquidStyle: ({ percent }) => {
          return {
            fill: percent > 0.45 ? "#5B8FF9" : "#FAAD14",
            stroke: percent > 0.45 ? "#5B8FF9" : "#FAAD14",
          };
        },
        color: () => "#5B8FF9",
      });
      plot.render();
      let data = 0.25;
      const interval = setInterval(() => {
        data += Math.min(Math.random() * 0.1, 0.1);
        if (data < 0.75) {
          liquidPlot.changeData(data);
        } else {
          clearInterval(interval);
        }
      }, 500);
    };
    onMounted(async () => {
      await loadData();
      initChart();
    });

    onUnmounted(() => {
      if (plot != null) {
        plot.destroy();
      }
    });

    return {
      root,
    };
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped>
</style>
